/**
 * output package name
 */
package com.kingdee.eas.crm.market.client;


import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.Date;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeNode;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.ctrl.kdf.table.KDTable;
import com.kingdee.bos.ctrl.kdf.table.event.KDTDataRequestEvent;
import com.kingdee.bos.ctrl.kdf.table.event.KDTMouseEvent;
import com.kingdee.bos.ctrl.kdf.table.event.KDTSelectEvent;
import com.kingdee.bos.ctrl.swing.tree.DefaultKingdeeTreeNode;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.dao.query.IQueryExecutor;
import com.kingdee.bos.metadata.IMetaDataPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SorterItemCollection;
import com.kingdee.bos.metadata.entity.SorterItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.ui.face.ItemAction;
import com.kingdee.bos.ui.face.UIFactory;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.commonquery.client.CommonQueryDialog;
import com.kingdee.eas.basedata.org.OrgStructureInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.common.client.OprtState;
import com.kingdee.eas.common.client.UIContext;
import com.kingdee.eas.common.client.UIFactoryName;
import com.kingdee.eas.crm.market.MarketSchemeFactory;
import com.kingdee.eas.crm.market.MarketSchemeInfo;
import com.kingdee.eas.crm.market.ThemeEnum;
import com.kingdee.eas.fdc.basedata.FDCBillInfo;
import com.kingdee.eas.fdc.basedata.FDCBillStateEnum;
import com.kingdee.eas.fdc.basedata.FDCCommonServerHelper;
import com.kingdee.eas.fdc.basedata.FDCHelper;
import com.kingdee.eas.fdc.basedata.IFDCBill;
import com.kingdee.eas.fdc.basedata.MoneySysTypeEnum;
import com.kingdee.eas.fdc.basedata.client.FDCClientUtils;
import com.kingdee.eas.fdc.market.client.MeasurePlanTargetListUI;
import com.kingdee.eas.fdc.market.client.SchemeQueryPanelUI;
import com.kingdee.eas.fdc.sellhouse.SellProjectInfo;
import com.kingdee.eas.fdc.sellhouse.client.FDCTreeHelper;
import com.kingdee.eas.framework.ICoreBase;
import com.kingdee.eas.util.client.EASResource;
import com.kingdee.eas.util.client.MsgBox;

/**
 * output class name
 */
public class MarketSchemeListUI extends AbstractMarketSchemeListUI
{
    /**
     * output class constructor
     */
    public MarketSchemeListUI() throws Exception
    {
        super();
        queryDlg = null;
    }

	public void onLoad()
	    throws Exception
	{
	       actionQuery.setEnabled(false);
	       initTree();
	       super.onLoad();
	       actionQuery.setEnabled(true);
	       btnAudit.setIcon(EASResource.getIcon("imgTbtn_audit"));
	       btnUnAudit.setIcon(EASResource.getIcon("imgTbtn_unaudit"));
	       btnEvaluation.setIcon(EASResource.getIcon("imgTbtn_evaluategrade"));
	       tblMain.getSelectManager().setSelectMode(2);
	       menuItemCancel.setVisible(false);
	       menuItemCancelCancel.setVisible(false);
	       actionCreateTo.setVisible(false);
	       actionCopyTo.setVisible(false);
	       actionTraceUp.setVisible(false);
	       actionTraceDown.setVisible(false);
	       menuBiz.setVisible(false);
	       tblMain.getColumn("EnterpriseSellPlan.planCost").getStyleAttributes().setHorizontalAlign(com.kingdee.bos.ctrl.kdf.util.style.Styles.HorizontalAlignment.RIGHT);
	       tblMain.getColumn("EnterpriseSellPlan.planCost").getStyleAttributes().setNumberFormat(FDCHelper.getNumberFtm(2));
	       tblMain.getColumn("EnterpriseSchemeEntry.factAmount").getStyleAttributes().setHorizontalAlign(com.kingdee.bos.ctrl.kdf.util.style.Styles.HorizontalAlignment.RIGHT);
	       tblMain.getColumn("EnterpriseSchemeEntry.factAmount").getStyleAttributes().setNumberFormat(FDCHelper.getNumberFtm(2));
	       tblMain.getColumn("EnterpriseSchemeEntry.contractAmount").getStyleAttributes().setHorizontalAlign(com.kingdee.bos.ctrl.kdf.util.style.Styles.HorizontalAlignment.RIGHT);
	       tblMain.getColumn("EnterpriseSchemeEntry.contractAmount").getStyleAttributes().setNumberFormat(FDCHelper.getNumberFtm(2));
	       tblMain.getColumn("EnterpriseSchemeEntry.payAmount").getStyleAttributes().setHorizontalAlign(com.kingdee.bos.ctrl.kdf.util.style.Styles.HorizontalAlignment.RIGHT);
	       tblMain.getColumn("EnterpriseSchemeEntry.payAmount").getStyleAttributes().setNumberFormat(FDCHelper.getNumberFtm(2));
	       tblMain.getColumn("name").setWidth(220);
	       actionRemove.setVisible(false);
	}
	
	protected String[] getLocateNames()
	{
	       String locateNames[] = new String[4];
	       locateNames[0] = "name";
	       locateNames[1] = "EnterprisePlanEntry.theme";
	       locateNames[2] = "EnterprisePlanEntry.describe";
	       locateNames[3] = "EnterpriseSellPlan.proceeding";
	       return locateNames;
	}
	
	protected void initTree()
	    throws Exception
	{
	       treeMain.setModel(FDCTreeHelper.getSellProjectTreeForSHE(actionOnLoad, MoneySysTypeEnum.SalehouseSys));
	       treeMain.expandAllNodes(true, (TreeNode)treeMain.getModel().getRoot());
	       treeMain.setSelectionRow(0);
	}
	
	protected void prepareUIContext(UIContext uiContext, ActionEvent e)
	{
	       super.prepareUIContext(uiContext, e);
	       ItemAction act = getActionFromActionEvent(e);
	       if(act.equals(actionAddNew))
	    {
	           int indexRow = tblMain.getSelectManager().getActiveRowIndex();
	           String enterprisePlanEntryId = (String)tblMain.getRow(indexRow).getCell("id").getValue();
	           uiContext.put("enterprisePlanEntryId", enterprisePlanEntryId);
	    }
	}
	
	public void actionEvaluation_actionPerformed(ActionEvent e)
	    throws Exception
	{
	       int curRow = tblMain.getSelectManager().getActiveRowIndex();
	       if(curRow >= 0)
	    {
	           String id = tblMain.getRow(curRow).getCell("EnterpriseScheme.id").getValue().toString();
	           MarketSchemeInfo info = MarketSchemeFactory.getRemoteInstance().getMarketSchemeInfo(new ObjectUuidPK(id));
	           if(info != null)
	               if(FDCBillStateEnum.AUDITTED.equals(info.getState()))
	            {
	                   UIContext context = new UIContext(this);
	                   context.put("ID", id);
	                   context.put("result", "result");
	                   UIFactory.createUIFactory(UIFactoryName.NEWTAB).create(MarketSchemeEditUI.class.getName(), context, null, OprtState.EDIT).show();
	            } else
	            {
	                   MsgBox.showInfo("\u5355\u636E\u672A\u5BA1\u6838\uFF0C\u4E0D\u80FD\u5F55\u5165\u6548\u679C\u8BC4\u4F30\u4FE1\u606F\uFF01");
	            }
	    }
	}
	
	public void actionUnAudit_actionPerformed(ActionEvent e)
	    throws Exception
	{
	       java.util.ArrayList idList = getSelectedIdValues();
	       ((IFDCBill)getBizInterface()).unAudit(idList);
	/* 1*/        FDCClientUtils.showOprtOK(this);
	       refresh(null);
	}
	
	public void actionAudit_actionPerformed(ActionEvent e)
	    throws Exception
	{
	       java.util.ArrayList idList = getSelectedIdValues();
	       ((IFDCBill)getBizInterface()).audit(idList);
	       FDCClientUtils.showOprtOK(this);
	       refresh(null);
	}
	
	protected void treeMain_valueChanged(TreeSelectionEvent e)
	    throws Exception
	{
	       refresh(null);
	}
	
	public void actionShowAllThemes_actionPerformed(ActionEvent e)
	    throws Exception
	{
	       refresh(null);
	}
	
	public void actionAddNew_actionPerformed(ActionEvent e)
	    throws Exception
	{
	       checkSelected();
	       super.actionAddNew_actionPerformed(e);
	       refresh(null);
	}
	
	private void checkObjectExists()
	    throws BOSException, EASBizException, Exception
	{
	       if(getSelectedKeyValue() == null)
	           return;
	       if(!getBizInterface().exists(new ObjectUuidPK(BOSUuid.read(getSelectedKeyValue()))))
	    {
	           refreshList();
	           throw new EASBizException(EASBizException.CHECKEXIST);
	    } else
	    {
	           return;
	    }
	}
	
	protected String getKeyFieldName()
	{
	       return "EnterpriseScheme.id";
	}
	
	protected void tblMain_tableClicked(KDTMouseEvent e)
	    throws Exception
	{
	       if(e.getType() == 1 && e.getButton() == 1 && e.getClickCount() == 2)
	    {
	           int index = tblMain.getSelectManager().getActiveRowIndex();
	           if(tblMain.getRow(index).getCell("EnterpriseScheme.id").getValue() == null)
	        {
	               MsgBox.showInfo("\u6CA1\u6709\u4F01\u5212\u5B9E\u65BD\uFF0C\u8BF7\u65B0\u589E\uFF01");
	               return;
	        }
	           super.tblMain_tableClicked(e);
	    }
	}
	
	protected boolean initDefaultFilter()
	{
	       return false;
	}
	
	protected CommonQueryDialog initCommonQueryDialog()
	{
	       if(queryDlg != null)
	           return queryDlg;
	       try
	    {
	           queryDlg = new CommonQueryDialog();
	           queryDlg.setOwner((Component)getUIContext().get("Owner"));
	           queryDlg.setParentUIClassName(getClass().getName());
	           queryDlg.setQueryObjectPK(mainQueryPK);
	           queryDlg.setHeight(350);
	           queryDlg.setWidth(570);
	           queryDlg.addUserPanel(getFilterUI());
	           queryDlg.setTitle("\u4F01\u5212\u5B9E\u65BD\u8FC7\u6EE4\u754C\u9762");
	           queryDlg.setShowSorter(true);
	           queryDlg.setUiObject(this);
	    }
	       catch(Exception e)
	    {
	    }
	       return queryDlg;
	}
	
	public SchemeQueryPanelUI getFilterUI()
	    throws Exception
	{
	       if(filterUI == null)
	           filterUI = new SchemeQueryPanelUI();
	       return filterUI;
	}
	
	public void setBtnState(KDTable table, ICoreBase iCoreBase, ItemAction audit, ItemAction unAudit, ItemAction edit, ItemAction del)
	    throws EASBizException, BOSException
	{
	       int index = table.getSelectManager().getActiveRowIndex();
	       if(index == -1)
	    {
	           audit.setEnabled(false);
	           unAudit.setEnabled(false);
	           edit.setEnabled(false);
	           del.setEnabled(false);
	           return;
	    }
	       SelectorItemCollection sel = new SelectorItemCollection();
	       sel.add("state");
	       String id = (String)table.getRow(index).getCell("EnterpriseScheme.id").getValue();
	       if(id == null)
	    {
	           audit.setEnabled(false);
	           unAudit.setEnabled(false);
	           edit.setEnabled(false);
	           del.setEnabled(false);
	           return;
	    }
	       FDCBillInfo info = (FDCBillInfo)iCoreBase.getValue(new ObjectUuidPK(id), sel);
	       if(FDCBillStateEnum.SUBMITTED.equals(info.getState()))
	    {
	           audit.setEnabled(true);
	           unAudit.setEnabled(false);
	           edit.setEnabled(true);
	           del.setEnabled(true);
	    } else
	       if(FDCBillStateEnum.AUDITTED.equals(info.getState()))
	    {
	           audit.setEnabled(false);
	           unAudit.setEnabled(true);
	           edit.setEnabled(false);
	           del.setEnabled(false);
	    } else
	       if(FDCBillStateEnum.SAVED.equals(info.getState()))
	    {
	           audit.setEnabled(false);
	           unAudit.setEnabled(false);
	           edit.setEnabled(true);
	           del.setEnabled(true);
	    } else
	       if(FDCBillStateEnum.AUDITTING.equals(info.getState()))
	    {
	           audit.setEnabled(false);
	           unAudit.setEnabled(false);
	           edit.setEnabled(false);
	           del.setEnabled(false);
	    }
	}
	
	protected void tblMain_tableSelectChanged(KDTSelectEvent e)
	    throws Exception
	{
	       setBtnState(tblMain, getBizInterface(), actionAudit, actionUnAudit, actionEdit, actionRemove);
	       int index = tblMain.getSelectManager().getActiveRowIndex();
	       if(index == -1)
	    {
	           btnEvaluation.setEnabled(false);
	           return;
	    }
	       String state = "";
	       if(tblMain.getRow(index).getCell("EnterprisePlanEntry.state").getValue() != null)
	    {
	           state = tblMain.getRow(index).getCell("EnterprisePlanEntry.state").getValue().toString();
	           if(ThemeEnum.Finish.getAlias().equals(state))
	               actionEvaluation.setEnabled(true);
	           else
	               actionEvaluation.setEnabled(false);
	    }
	       if(tblMain.getRow(index).getCell("EnterpriseScheme.id").getValue() == null)
	    {
	           if(ThemeEnum.Canceled.getAlias().equals(state))
	               actionAddNew.setEnabled(false);
	           else
	               actionAddNew.setEnabled(true);
	    } else
	    {
	           actionAddNew.setEnabled(false);
	    }
	}
	
	public boolean isIgnoreRowCount()
	{
	       return false;
	}
	
	protected IQueryExecutor getQueryExecutor(IMetaDataPK pk, EntityViewInfo viewInfo)
	{
	       EntityViewInfo view = (EntityViewInfo)viewInfo.clone();
	       DefaultKingdeeTreeNode node = (DefaultKingdeeTreeNode)treeMain.getLastSelectedPathComponent();
	       FilterInfo filter = new FilterInfo();
	       if(node != null)
	    {
	           if(node.getUserObject() instanceof SellProjectInfo)
	        {
	               SellProjectInfo info = (SellProjectInfo)node.getUserObject();
	               filter.getFilterItems().add(new FilterItemInfo("EnterprisePlan.sellProject.id", info.getId().toString()));
	        } else
	           if(node.getUserObject() instanceof OrgStructureInfo)
	               filter.getFilterItems().add(new FilterItemInfo("EnterprisePlan.sellProject.id", MeasurePlanTargetListUI.getAllProjectNodeId(node), CompareType.INCLUDE));
	           if(!kDCheckBox1.isSelected())
	               filter.getFilterItems().add(new FilterItemInfo("useing", Boolean.TRUE));
	    }
	       try
	    {
	           if(view.getFilter() != null)
	               view.getFilter().mergeFilter(filter, "and");
	           else
	               view.setFilter(filter);
	           SorterItemCollection sort = new SorterItemCollection();
	           sort.add(new SorterItemInfo("EnterprisePlan.id"));
	           sort.add(new SorterItemInfo("seq"));
	           sort.add(new SorterItemInfo("EnterpriseSellPlan.seq"));
	           view.setSorter(sort);
	    }
	       catch(BOSException e)
	    {
	           e.printStackTrace();
	    }
	       return super.getQueryExecutor(pk, view);
	}
	
	protected String getEditUIName()
	{
	       return MarketSchemeEditUI.class.getName();
	}
	
	
	protected String getEditUIModal()
	{
	       return UIFactoryName.NEWTAB;
	}
	
	protected void afterTableFillData(KDTDataRequestEvent e)
	{
	       super.afterTableFillData(e);
	       mergerTable(tblMain, new String[] {
	           "EnterprisePlan.id"
	    }, new String[] {
	           "name", "useing"
	    });
	       mergerTable(tblMain, new String[] {
	           "id"
	    }, new String[] {
	           "EnterprisePlanEntry.theme", "EnterprisePlanEntry.state", "EnterprisePlanEntry.describe"
	    });
	}
	
	public void mergerTable(KDTable table, String coloum[], String mergeColoum[])
	{
	       int merger = 0;
	       Date nowTime = new Date();
	       try
	    {
	           nowTime = FDCCommonServerHelper.getServerTime();
	    }
	       catch(BOSException e)
	    {
	           e.printStackTrace();
	    }
	       for(int i = 0; i < table.getRowCount(); i++)
	    {
	           boolean isEnd = false;
	           if(table.getRow(i).getCell("EnterpriseSellPlan.state") != null && table.getRow(i).getCell("EnterpriseSellPlan.state").getValue() != null && table.getRow(i).getCell("EnterpriseSellPlan.state").getValue().toString().equals("\u5DF2\u5B8C\u6210"))
	               isEnd = true;
	           if(!isEnd && table.getRow(i).getCell("EnterpriseSellPlan.endTime") != null)
	        {
	               Date startTime = (Date)table.getRow(i).getCell("EnterpriseSellPlan.endTime").getValue();
	               if(startTime != null && startTime.before(nowTime))
	            {
	                   for(int j = 0; j < table.getColumnCount(); j++)
	                       if(table.getColumn(j).getKey().indexOf("EnterpriseSellPlan") == 0 || table.getColumn(j).getKey().indexOf("MarketScheme") == 0)
	                           table.getRow(i).getCell(table.getColumn(j).getKey()).getStyleAttributes().setBackground(Color.pink);
	
	            }
	        }
	           if(i > 0)
	        {
	               boolean isMerge = true;
	               for(int j = 0; j < coloum.length; j++)
	            {
	                   Object curRow = table.getRow(i).getCell(coloum[j]).getValue();
	                   Object lastRow = table.getRow(i - 1).getCell(coloum[j]).getValue();
	                   if(getString(curRow).equals("") || getString(lastRow).equals("") || !getString(curRow).equals(getString(lastRow)))
	                {
	                       isMerge = false;
	                       merger = i;
	                }
	            }
	
	               if(isMerge)
	            {
	                   for(int j = 0; j < mergeColoum.length; j++)
	                       table.getMergeManager().mergeBlock(merger, table.getColumnIndex(mergeColoum[j]), i, table.getColumnIndex(mergeColoum[j]));
	
	            }
	        }
	    }
	
	}
	
	private static String getString(Object value)
	{
	       if(value == null)
	           return "";
	       if(value != null && value.toString().trim().equals(""))
	           return "";
	       else
	           return value.toString();
	}
	
	protected void refresh(ActionEvent e)
	    throws Exception
	{
	       boolean isSelect = false;
	       int rowIndex = tblMain.getSelectManager().getActiveRowIndex();
	       if(rowIndex == -1)
	           isSelect = true;
	       super.refresh(e);
	       if(tblMain.getRowCount() == 0)
	    {
	           actionAudit.setEnabled(false);
	           actionUnAudit.setEnabled(false);
	           actionEdit.setEnabled(false);
	           actionRemove.setEnabled(false);
	           actionAddNew.setEnabled(false);
	           actionEvaluation.setEnabled(false);
	    }
	       if(isSelect)
	           tblMain.getSelectManager().select(0, 0);
	}
	
	protected boolean isIgnoreCUFilter()
	{
	       return true;
	}
	
	private CommonQueryDialog queryDlg;
	SchemeQueryPanelUI filterUI;
    /**
     * output getBizInterface method
     */
    protected com.kingdee.eas.framework.ICoreBase getBizInterface() throws Exception
    {
        return com.kingdee.eas.crm.market.MarketSchemeFactory.getRemoteInstance();
    }

    /**
     * output createNewData method
     */
    protected com.kingdee.bos.dao.IObjectValue createNewData()
    {
        com.kingdee.eas.crm.market.MarketSchemeInfo objectValue = new com.kingdee.eas.crm.market.MarketSchemeInfo();
		
        return objectValue;
    }

}